import { Button, message, Modal, Space, } from 'antd';
import ProCard from '@ant-design/pro-card';
import React, { useState, useRef, } from 'react';
import { Access, getDvaApp, history, useAccess, } from 'umi';

import $utils from '@/utils/utils';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable, { ActionType, ProColumns } from '@ant-design/pro-table';
import { CabinetCellByCab, CabinetCellList, OpenCell, UpdateCellGlitch, UpdateCellIdle } from '@/services/cabinet';
import { cellTypes, cellStatus, codeTypeData } from '@/utils/common';


const CellDetail: React.FC = () => {
    // 获取权限
    const access = useAccess();

    // 解决无法调用dispatch
    const dispatch = getDvaApp()._store.dispatch;
    const type_actionRef = useRef<ActionType>();
    const actionRef = useRef<ActionType>();
    const [cur_id, setCur_id] = useState<string>();
    const [current, setCurrent] = useState<number>(1);
    const [pageSize, setPageSize] = useState<number>(20);

    const [selectedRowKeys, setSelectedRowKeys] = useState<any>({ 1: [] });    // TODO 已选择格口ids
    const [cellList, setCellList] = useState<any>();    //  格口列表

    const l_state: any = history.location.state;
    if (!cur_id && !l_state) {
        history.push('/BasicConfig/Cabinet');
    }

    const id: string = l_state?.data?.id || '';
    //  同path更新,只更新state时，通过id重新请求数据
    if (l_state && id && (!cur_id || cur_id !== id)) {
        setCur_id(id);
    }
    else if (l_state && !id && cur_id !== id) {
        setCur_id('');
    }

    // 单个格口打开确认弹框
    const openCell_confirm = (data: any) => {
        Modal.confirm({
            className: 'again-send',
            icon: false,
            width: '320px',
            title: (<div style={{ textAlign: 'center', fontSize: 18, color: '#000' }}>打开格口</div>),
            content: (<div>
                <div style={{ textAlign: 'center', color: 'rgba(136, 136, 136, 100)', fontSize: 15, marginBottom: 12, }}>确定打开该格口？</div>
            </div>),
            centered: true,
            maskClosable: true,
            okText: '确认',
            cancelText: '取消',
            onOk: async () => {
                // 双面柜 参数使用code
                const params = l_state?.data?.model === 4 ? {
                    cabId: data.cabinetId,
                    cellCodes: [data.code],
                    terminal: 'trench'
                } : {
                    cellIds: [data.id],
                    terminal: 'trench'
                }
                const msg = await OpenCell(params);
                if (msg.code === 0) {
                    message.success('操作成功');
                    type_actionRef && (type_actionRef?.current?.reload());
                    actionRef && (actionRef?.current?.reload());
                }
            }
        });
    };

    // 格口占用情况 
    const latticeType_columns: ProColumns<any>[] = [
        {
            title: '',
            align: 'center',
            dataIndex: 'cellType',
            width: '100px',
            valueType: 'select',
            fieldProps: {
                options: cellTypes
            }
        },
        {
            title: '空闲',
            dataIndex: 'idle',
            align: 'center',
            width: '100px',
        },
        {
            title: '占用',
            dataIndex: 'occupied',
            align: 'center',
            width: '100px',
        },
        {
            title: '故障',
            dataIndex: 'maintain',
            align: 'center',
            width: '100px',
        },
        {
            title: '总数',
            dataIndex: 'cellCount',
            align: 'center',
            width: '100px',
        },
    ];

    // 格口列表状态
    const cellTypeStatus_columns: ProColumns<any>[] = [
        {
            title: '格口描述',
            align: 'center',
            dataIndex: 'desc',
            width: '100px',
            onCell: (_: any, index: any) => {
                const span: number = $utils.getRowSpanCount(cellList, 'desc', index) || 0;
                return {
                    rowSpan: +span
                }
            },
            search: {
                transform: (value: string) => ({ cellDesc: value })
            },
        },
        {
            title: '格口编号',
            align: 'center',
            dataIndex: 'codeType',
            valueType: 'select',
            width: '100px',
            search: false,
            hideInTable: l_state?.data?.model === 4 ? false : true,
            fieldProps: {
                options: codeTypeData
            },
            render: (dom: any, data: any) => {
                return (
                    <div>{dom}({data.code})</div>
                )
            }
        },
        {
            title: '格口类型',      // 格口类型 10901 大; 10902 中; 10903 小;10904 超小;10911 超大
            dataIndex: 'type',
            align: 'center',
            width: '100px',
            valueType: 'select',
            fieldProps: {
                options: cellTypes,
            },
            onCell: (_: any, index: any) => {
                const span: number = $utils.getRowSpanCount(cellList, 'desc', index) || 0;
                return {
                    rowSpan: +span
                }
            },
            search: {
                transform: (value: string) => ({ cellType: value })
            }
        },
        {
            title: '格口状态',
            dataIndex: 'status',
            align: 'center',
            width: '100px',
            valueType: 'select',
            fieldProps: {
                options: cellStatus
            },
            onCell: (_: any, index: any) => {
                const span: number = $utils.getRowSpanCount(cellList, 'desc', index) || 0;
                return {
                    rowSpan: +span
                }
            },
            search: {
                transform: (value: string) => ({ cellStatus: value })
            }
        },
        {
            title: '占用类型',
            dataIndex: 'maintain',
            search: false,
            align: 'center',
            width: '100px',
            onCell: (_: any, index: any) => {
                const span: number = $utils.getRowSpanCount(cellList, 'desc', index) || 0;
                return {
                    rowSpan: +span
                }
            },
            render: (text: any, record: any) => {
                return (<div>{record.status === 11102 ? '派件' : '--'}</div>)
            }
        },
        {
            title: '操作',
            width: 48,
            render: (val: any, record: any) => (
                <>
                    <Button type="link" key={record.id} onClick={() => {
                        const newTab = {
                            name: `查看${record.desc}(${record.code})格口轨迹`,
                            path: '/BasicConfig/Cabinet/cellTrack',
                            state: {
                                status: 'detail',
                                data: record
                            }
                        };
                        // 设置当前tab对象
                        $utils.setNewTab(dispatch, newTab);
                        $utils.addTab(dispatch, newTab)
                        history.push({
                            pathname: '/BasicConfig/Cabinet/cellTrack',
                            state: {
                                status: 'detail',
                                data: record
                            }
                        });
                    }}>
                        格口轨迹
                    </Button>
                    <Button type="link" key={record.id} onClick={() => {
                        const newTab = {
                            name: `查看${record.desc}(${record.code})历史订单`,
                            path: '/BasicConfig/Cabinet/cellHistoryOrder',
                            state: {
                                status: 'detail',
                                data: record
                            }
                        };
                        // 设置当前tab对象
                        $utils.setNewTab(dispatch, newTab);
                        $utils.addTab(dispatch, newTab)
                        history.push({
                            pathname: '/BasicConfig/Cabinet/cellHistoryOrder',
                            state: {
                                status: 'detail',
                                data: record
                            }
                        });
                    }}>
                        历史订单
                    </Button>
                    <Button type="link" key={record.id} onClick={() => {
                        openCell_confirm(record);
                    }}>
                        打开格口
                    </Button>
                </>
            ),
        },
    ];

    const modalShow = (type: number) => {
        const title = type === 1 ? '确定置空闲？' : type === 2 ? '确定置故障？' : '确定打开格口？', content = type === 1 ? '如果格口有未取走订单，将自动变为废弃！' : type === 2 ? '如果格口有未取走订单，将自动变为废弃！' : '';

        const cellIds = Object.values(selectedRowKeys).flat().join();
        if (cellIds.length === 0) { message.warning('请选择格口'); return; }

        Modal.confirm({
            className: 'again-send',
            icon: false,
            width: '360px',
            title: (<div style={{ textAlign: 'center', fontSize: 18, color: '#000' }}>{title}</div>),
            content: (<div>
                <div style={{ textAlign: 'center', color: 'rgba(136, 136, 136, 100)', fontSize: 15, marginBottom: 12, }}>{content}</div>
            </div>),
            centered: true,
            maskClosable: true,
            okText: '确认',
            cancelText: '取消',
            onOk: async () => {
                const params = l_state?.data?.model === 4 ? {
                    cabId: l_state?.data?.id,
                    cellCodes: cellIds,
                    terminal: 'trench'
                } : {
                    cellIds: cellIds,
                    terminal: 'trench'
                };
                // 置空闲
                let msg = null;
                if (type === 1) {
                    msg = await UpdateCellIdle(params);
                }
                else if (type === 2) {
                    msg = await UpdateCellGlitch(params);
                }
                else if (type === 3) {
                    msg = await OpenCell(params);
                }
                if (msg.code === 0) {
                    message.success('操作成功');
                    setSelectedRowKeys([]);
                    type_actionRef && (type_actionRef?.current?.reload());
                    actionRef && (actionRef?.current?.reload());
                }
            }
        });
    };

    return (
        <PageContainer>
            {cur_id && <ProCard style={{ marginTop: 8 }} gutter={8} >
                <ProTable
                    actionRef={type_actionRef}
                    rowKey="cellType"
                    search={false}
                    tableAlertRender={false}
                    pagination={false}
                    toolBarRender={false}
                    columns={latticeType_columns}
                    params={{ cabId: cur_id }}
                    request={async (params) => {
                        const msg = await CabinetCellByCab(params);
                        if (msg.code === 0) {

                        }
                        return {
                            data: msg.body || [],
                            success: msg.code === 0,
                            total: msg.body?.length,
                        }
                    }}
                />
            </ProCard>}
            {cur_id && <ProCard style={{ marginTop: 8 }} gutter={8} >
                <ProTable
                    rowKey={l_state?.data?.model === 4 ? "code" : "cellId"}
                    actionRef={actionRef}
                    tableAlertRender={false}
                    pagination={{
                        current: current,
                        pageSize: pageSize,
                        showSizeChanger: true,
                        size: 'small',
                        onShowSizeChange: (current, pageSize) => {
                            setCurrent(current);
                            setPageSize(pageSize);
                        }
                    }}
                    search={{
                        labelWidth: 120,
                        defaultCollapsed: false,
                        collapseRender: () => false,
                    }}
                    title={() => [
                        <Access key="index" accessible={access.can_numAll.create}>
                            <Space>
                                <Button type="primary" onClick={() => {
                                    // console.log("qqq", Object.values(selectedRowKeys).flat());
                                    modalShow(1);
                                }}>置空闲</Button>
                                <Button type="primary" onClick={() => {
                                    modalShow(2);
                                }}>置故障</Button>
                                <Button type="primary" onClick={() => {
                                    modalShow(3);
                                }}>打开格口</Button>
                            </Space>
                        </Access>
                    ]}
                    toolBarRender={false}
                    columns={cellTypeStatus_columns}
                    params={{ cabId: cur_id }}
                    request={async (params) => {
                        const msg = await CabinetCellList(params);
                        if (msg.code === 0) {
                            setCellList(msg.body?.list);
                        }
                        return {
                            data: msg.body?.list || [],
                            success: msg.code === 0,
                            total: msg.body?.count,
                        }
                    }}
                    rowSelection={{
                        // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
                        // 注释该行则默认不显示下拉选项
                        selectedRowKeys: selectedRowKeys[current],
                        onChange: (newSelectedRowKeys: React.Key[]) => {
                            const newSelected = { ...selectedRowKeys };
                            newSelected[current] = newSelectedRowKeys;
                            setSelectedRowKeys(newSelected);
                        },
                    }}
                />
            </ProCard>}
        </PageContainer >
    );
};

export default CellDetail;
